package com.flying.refdata.service;

import com.flying.refdata.model.equity.EquityInfo;
import com.flying.refdata.model.equity.MarketData;
import com.flying.refdata.repository.equity.MarketDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MarketDataService {
    @Autowired
    private MarketDataRepository repository;
    private Map<String, MarketData> marketDataCache = new ConcurrentHashMap<>();

    public MarketData getMarketData(EquityInfo info, int date) {
        String key = info.getCode() + date;
        if (marketDataCache.containsKey(key)) return marketDataCache.get(key);
        MarketData marketData = repository.findByEquityInfoAndDate(info, date);
        if (marketData == null) return null;
        marketDataCache.put(key, marketData);
        return marketData;
    }

    public MarketData saveMarketData(MarketData marketData) {
        if (marketData != null) {
            String key = marketData.getEquityInfo().getCode() + marketData.getDate();
            marketData = repository.save(marketData);
            marketDataCache.put(key, marketData);
        }
        return marketData;
    }

    public MarketData getOrCreateMarketData(EquityInfo info, int date) {
        MarketData data = getMarketData(info, date);
        if (data == null) {
            data = new MarketData();
            data.setEquityInfo(info);
            data.setDate(date);
        }
        return data;
    }

    public List<MarketData> saveMarketData(Iterable<MarketData> marketDatas) {
        List<MarketData> result = new ArrayList<>();
        if (marketDatas == null) {
            return result;
        }
        for (MarketData marketData : marketDatas) {
            result.add(saveMarketData(marketData));
        }
        return result;
    }
}
